<template>
    <div class="detail">
        <!-- 口语 -->
        <template v-if="routeQuery.type == '1'">
            <spoken :listData="detailData" mode="detail"/>
        </template>
        <!-- 笔试机考 -->
        <template v-else>
            <write :listData="detailData" mode="detail"/>
        </template>

        <!-- 同场回忆 -->
        <div class="more-memory" v-if="detailData.onSiteExamCount > 0" @click="viewSame">
            <div class="users">
                <div class="avatar" v-for="(item, index) in detailData.onSiteExamAvatar" :key="index" :style="{transform: `translateX(${-25 * index}rpx)`}">
                    <image 
                        :src="item" 
                        alt=""
                        v-if="!item['type']"
                    />
                    <div v-else class="more">
                        <div>
                            <text class="point" v-for="(item, index) in 3" :key="index"></text>
                        </div>
                    </div>
                </div>
            </div>
            <text class="text">{{detailData.onSiteExamCount}}条同场回忆</text>
        </div>

        <!-- 评论 -->
        <comment
            id="comment"
            ref="commentRef"
            :list="commentList" 
            :loadStatus="loadStatus" 
            :total="commentCount"
            :scene="scene"
            @to-reply="handleReply"
            @reply-pop="replyPop"
        />

        <!-- 发评论 -->
        <div class="footer" :style="{bottom: bottom}" :class="{transition: focus}">
            <div class="input-warp">
                <image class="edit" src="@/static/icon-edit.png" alt=""></image>
                <input 
                    class="uni-input" 
                    placeholder="评论一下" 
                    confirm-type="send"
                    type="text"
                    v-model.trim="content"
                    :focus="focus"
                    :adjust-position="false"
                    :maxlength="100"
                    @confirm="sendComment"
                    @keyboardheightchange="keyboardheightchange"
                    @blur="onBlur"
                    @focus="onFocus"
                />
            </div>
            <div class="right-info">
                <button open-type="share" class="share-btn">
                    <image class="share" src="@/static/icon-share.png" alt=""></image>
                    <text class="num">{{formatNum(detailData.shares || 0)}}</text>
                </button>
                <div class="star" @click="handleStar">
                    <image v-show="!detailData.isLike" class="share" src="@/static/icon-star.png" alt=""></image>
                    <image v-show="detailData.isLike" class="share" src="@/static/icon-star-active.png" alt=""></image>
                    <text class="num">{{formatNum(detailData.likes || 0)}}</text>
                </div>
            </div>
        </div>

        <!-- 点击自己的评论的弹窗 -->
        <uni-popup 
            ref="popup" 
            type="bottom" 
            border-radius="40px 40px 0 0" 
            background-color="#F3F3F4"
            @change="popChange"
        >
            <div class="reply-popup">
                <div class="item" @click="handleReply(replyParams)">
                    <image src="@/static/icon-reply.png"></image>
                    <text>回复</text>
                </div>
                <div class="item del" @click="delReply">
                    <image src="@/static/icon-del.png"></image>
                    <text>删除</text>
                </div>
                <div class="item cancel" @click="cancel">
                    <text>取消</text>
                </div>
            </div>
        </uni-popup>
    </div>
</template>

<script>
import Spoken from '../index/components/speech-item.vue'
import Write from '../index/components/write-item.vue'
import Comment from './components/comment.vue'
import UniPopup from '@/components/uni-popup/uni-popup.vue'
import {imgPreFix} from '@/common/util/util'
import {
    apiSpeakDetail, 
    apiWriteDetail,
    apiListComment,
    apiLike,
    apiAddComment,
    apiRemoveComment,
    apiCountComment,
    apiAddShares
} from '@/api/memory'
export default {
    components: {
        Spoken,
        Write,
        Comment,
        UniPopup
    },
    data() {
        return {
            routeQuery: {}, // 路由参数
            detailData: {},
            commentPage: {
                pageSize: 10,
                pageNum: 1
            },
            commentList: [], // 评论列表
            loadStatus: 'more',
            focus: false,
            bottom: 0,
            content: '', // 评论内容
            replyParams: {}, // 被回复人信息
            scene: '', // 场景值，判断是否朋友圈打开
            commentCount: 0, // 评论数
            needRefresh: true // 退出页面是否需要刷新列表页
        }
    },
    async onLoad(option){
        this.routeQuery = option
        this.scene = wx.getLaunchOptionsSync().scene
        this.getDetail()
        this.getCommentCount()
        await this.getComment()
        await this.$nextTick()
        setTimeout(() => {
            if(this.routeQuery.scroll == 'comment'){
                uni.pageScrollTo({
                    selector: '#comment',
                    duration: 500
                })
            }
        }, 100);
    },
    onShow(){
        
    },
    onReachBottom(){
        if(this.loadStatus !== 'noMore'){
            this.commentPage.pageNum++
            this.getComment()
        }
    },
    onShareAppMessage(){
        this.addShare()
        return {
            title: '新东方雅思搜题',
            imageUrl: `${imgPreFix()}/share_img.jpg`
        }
    },
    onShareTimeline(){
        this.addShare()
        return {
            imageUrl: `${imgPreFix()}/share_img.jpg`
        }
    },
    onUnload(){
        if(this.needRefresh){ // 如果点击同场回忆退出页面，会触发同场回忆的刷新，避免刷新多次
            uni.$emit('refresh')
        }
    },
    methods: {
        // 增加分享数
        addShare(){
            apiAddShares({ 
                id: this.detailData.id
            }).then(res => {
                if(res.code == 200){
                    this.detailData.shares+=1
                }
            }).catch(err => {
                console.log(err, 'err')
            })
        },
        // 查看同场回忆
        viewSame(){
            this.needRefresh = false
            const time = this.detailData.speakExamDate || this.detailData.examDate
            uni.navigateBack({
                success(){
                    uni.$emit('same-time', {examDate: time})
                }
            })
        },

        // 点击自己评论显示弹窗
        replyPop(data){
            this.$refs.popup.open()
            this.replyParams = data
        },

        // 删除评论
        delReply(){
            this.$tip.confirm('您确定删除当前评论吗？', true).then(res => {
                apiRemoveComment({ 
                    id: this.replyParams.id
                 }).then(res => {
                    if(res.code == 200){
                        this.$tip.toast('删除成功')
                        this.commentPage.pageNum = 1
                        this.commentList = []
                        this.replyParams = {}
                        this.$refs.popup.close()
                        this.getCommentCount()
                        this.getComment()
                    }
                }).catch(err => {
                    console.log(err, 'err')
                })

            }).catch(err => {
                console.log(err)
            })
        },

        cancel(){
            this.$refs.popup.close()
            this.replyParams = {}
        },

        popChange({show}){
            if(!show){
                this.cancel()
            }
        },

        // 点赞
        handleStar(){
            // 朋友圈打开
            if(this.scene == 1154) return this.$tip.toast('请前往小程序使用完整服务')
            apiLike({ 
                type: this.routeQuery.type,
                targetId: this.detailData.id,
                isLike: this.detailData.isLike ? 0 : 1
             }).then(res => {
                if(res.code == 200){
                    this.detailData.isLike = !this.detailData.isLike
                    if(this.detailData.isLike){
                        this.detailData.likes+=1
                        this.$tip.toast('点赞成功')
                    }else {
                        this.detailData.likes-=1
                        // this.$tip.toast('取消点赞成功')
                    }
                }
            }).catch(err => {
                console.log(err, 'err')
            })
        },

        formatNum(num){
            return num > 999 ? '999+' : num
        },

        // 输入框失焦隐藏键盘，恢复输入框位置
        onBlur(){
            this.focus = false
            this.bottom = 0
        },

        onFocus(){
            this.focus = true
        },

        // 点击回复拉起键盘 data是被回复人数据
        async handleReply(data){
            this.$refs.popup && this.$refs.popup.close()
            await this.$nextTick()
            this.focus = true
            this.replyParams = data
        },

        // 发评论
        sendComment(){
            if(!this.content) return this.$tip.toast('评论内容不能为空')
            apiAddComment({ 
                comment: this.content,
                mainId: this.routeQuery.id,
                ...this.replyParams
             }).then(res => {
                if(res.code == 200){
                    this.$tip.toast(res.data ? '评论成功' : '评论审核中')
                    this.content = ''
                    this.focus = false
                    this.replyParams = {}
                    this.commentPage.pageNum = 1
                    this.commentList = []
                    this.getComment()
                    this.getCommentCount()
                    this.$refs.commentRef.page = 0
                }
            }).catch(err => {
                console.log(err, 'err')
            })
        },

        // 评论数
        getCommentCount(){
            apiCountComment({ 
                id: this.routeQuery.id
             }).then(res => {
                if(res.code == 200){
                    this.commentCount = res.data || 0
                }
            }).catch(err => {
                console.log(err, 'err')
            })
        },

        // 监听键盘高度，弹起时把输入框定位到键盘上方
        keyboardheightchange({detail: {height = 0}}){
            this.bottom = `${height}px`
        },

        // 评论列表
        getComment(){
            this.loadStatus = 'loading'
            return apiListComment({ 
                ...this.commentPage,
                mainId: this.routeQuery.id
             }).then(res => {
                if(res.code == 200){
                    this.commentList.push(...(res.data.rows || []))
                    if(this.commentList.length >= res.data.total){
                        this.loadStatus = 'noMore'
                    }
                }
            }).catch(err => {
                console.log(err, 'err')
            })
        },

        // 回忆详情
        getDetail(){
            this.$tip.loading()
            const {type, id}  = this.routeQuery
            const api = type == 1 ? apiSpeakDetail : apiWriteDetail
            api({ id }).then(res => {
                if(res.code == 200){
                    let {onSiteExamAvatar: list, onSiteExamCount, contentList} = res.data
                    if(onSiteExamCount > 6){
                        list.push({type: 'more'})
                    } 
                    if(this.routeQuery.type == 1){
                        contentList = contentList.map(item => {
                            return {
                                ...item,
                                topics: item.isNewTopic ? [{topicType: "疑似新题", type: "new"}] : item.topics
                            }
                        })
                    }
                    this.detailData = {
                        ...res.data,
                        onSiteExamAvatar: list,
                        contentList
                    }
                }
            }).catch(err => {
                console.log(err, 'err')
            }).finally(res => {
                this.$tip.loaded()
            })
        }
    },
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
@function toRem($rpx){  //$rpx为需要转换的字号
    @return #{$rpx * 100 / 750 / 4}rem; 
}
.detail{
    background-color: #F6F8FC;
    min-height: 100%;
    padding: toRem(20) toRem(30) toRem(200);
    box-sizing: border-box;
    .more-memory{
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: toRem(20);
        background-color: #fff;
        border-radius: toRem(10);
        box-sizing: border-box;
        color: #333;
        font-size: toRem(24);
        margin-bottom: toRem(20);
        .users{
            position: relative;
            display: inline-flex;
            align-items: center;
            .avatar{
                position: relative;
                width: toRem(48);
                height: toRem(48);
                border-radius: 50%;
                image{
                    width: 100%;
                    height: 100%;
                    border-radius: 50%;
                }
            }
            .more{
                background-color: #EAEEF6;
                text-align: center;
                position: relative;
                width: 100%;
                height: 100%;
                border-radius: 50%;
                &>div{
                    line-height: 0;
                    position: absolute;
                    top: 50%;
                    transform: translate(0,-50%);
                    width: 100%;
                    border-radius: 50%;
                }
                .point{
                    display: inline-block;
                    width: toRem(6);
                    height: toRem(6);
                    border-radius: 50%;
                    background-color: #fff;
                    &:nth-child(2n){
                        margin: 0 toRem(6) 0;
                    }
                }
            }
        }
    }
    .footer{
        transition: all .4s;
        -webkit-transition: all .3s;
        width: 100%;
        position: fixed;
        bottom: 0;
        left: 0;
        background-color: #fff;
        height: toRem(160);
        padding: 0 toRem(30) 0;
        box-sizing: border-box;
        z-index: 50;
        display: flex;
        align-items: center;
        .input-warp{
            display: flex;
            align-items: center;
            padding: toRem(20) toRem(30);
            background-color: #F6F8FC;
            flex: 1;
            height: toRem(68);
            box-sizing: border-box;
            border-radius: toRem(34);
            // min-width: toRem(420);
            .edit{
                width: toRem(20);
                height: toRem(20);
                margin-right: toRem(12);
            }
            .uni-input{
                background-color: #F6F8FC;
                height: 100%;
                padding: 0;
                color: #333;
            }
            input[placeholder]{
                font-size: toRem(24);
            }
        }
        .right-info{
            display: flex;
            align-items: center;
            justify-content: space-between;
            // flex: 1;
            margin-left: toRem(70);
        }
        .share{
            width: toRem(32);
            height: toRem(31);
        }
        .star{
            display: inline-flex;
            align-items: center;
            margin-left: toRem(40);
            image{
                margin-left: 0;
            }
        }
        .num{
            color: #999;
            font-size: toRem(24);
            margin-left: toRem(10);
        }
    }
    
    .reply-popup{
        height: toRem(450);
        background-color: #F3F3F4;
        padding: toRem(53) toRem(30) 0;
        box-sizing: border-box;
        border-radius: toRem(40) toRem(40) 0 0;
        .item{
            width: 100%;
            height: toRem(100);
            background-color: #fff;
            box-sizing: border-box;
            margin-bottom: toRem(20);
            font-size: toRem(28);
            color: #333;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: toRem(10);
            image{
                width: toRem(24);
                height: toRem(24);
                margin-right: toRem(20);
            }
            &:last-child{
                margin-bottom: 0;
            }
        }
        .del{
            color: #FD453D;
        }
        .cancel{
            color: #999;
        }
    }
}
.share-btn{
    border: none;
    padding: 0;
    margin: 0;
    line-height: 0;
    background-color: rgba(0,0,0,0);
    display: inline-flex;
    align-items: center;
    &::after{
        border: none;
    }
}
 
</style>
